<script setup>
import {ref, reactive, computed, onMounted, nextTick, watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Upload, Delete, Search } from '@element-plus/icons-vue'
import { utils, writeFileXLSX } from 'xlsx'
import {getUsersApi, addUserApi, getUserInfoApi, editUserApi, deleteUserApi} from "@/api/users.js";
import dayjs from "dayjs";
import {useClassStore} from '@/stores/class.js'
import AuthButton from '@/components/AuthButton.vue'

// 获取存储班级信息的仓库
const classStore = useClassStore()
// 存储所有用户信息
const userList = ref([])
// 当前页
const currentPageNum = ref(1)
// 每页有多少行数据
const pageSize = ref()
// 总页数
const totalPageNum = ref()

// 获取所有用户基本信息
const getUserList = async () => {
  let res = await getUsersApi()
  if (res.code == 200) {
    const result = res.result
    let resUserList = result.records
    userList.value = resUserList
    currentPageNum.value = result.current
    pageSize.value = result.size
    totalPageNum.value = result.total
  } else {
    ElMessage.error(res.message)
  }
}

onMounted(() => {
  getUserList()
})

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref()
const selectedUsers = ref([])
const currentUser = ref({})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  gender: '',
  organization: undefined
})

// 新增用户和编辑用户使用的用户表单
const userForm = reactive({
  name: '',
  gender: '',
  userId: '',
  password: '',
  hometown: '',
  email: '',
  weChatId: '',
  classInfo: [],
  classInfoText: '',
  avatar: 'https://placehold.co/100x100',
  telephone: '',
  birthDate: '',
  structure: [],
  structureText: ''
})

// 用户表单验证规则
const userFormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  userId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  hometown: [{ required: true, message: '请输入居住地址', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  weChatId: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
  classInfo: [{ required: true, message: '请选择所属班级', trigger: 'change' }],
  telephone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  birthDate: [{ required: true, message: '请输入出生日期', trigger: 'blur' }],
  structure: [{ required: true, message: '请选择组织结构', trigger: 'change' }],
}

// 检测dialogTitle.value，控制新增用户和编辑用户对password的验证规则
watch(dialogTitle, (newVal) => {
  if (newVal == '编辑用户') userFormRules.password[0].required = false
  else userFormRules.password[0].required = true
})

// 班级架构-河南工业和信息化职业学院五级结构
const organizationOptions = [
  {
    value: '河南工业和信息化职业学院', label: '河南工业和信息化职业学院',
    children: [
      {
        value: '计算机学院', label: '计算机学院',
        children: [
          {
            value: '计算机应用技术', label: '计算机应用技术',
            children: [
              {
                value: '2025级', label: '2025级',
                children: [
                  { value: '1班', label: '1班' },
                  { value: '2班', label: '2班' },
                  { value: '3班', label: '3班' }
                ]
              },
              {
                value: '2024级', label: '2024级',
                children: [
                  { value: '1班', label: '1班' },
                  { value: '2班', label: '2班' },
                  { value: '3班', label: '3班' }
                ]
              },
              {
                value: '2023级', label: '2023级',
                children: [
                  { value: '1班', label: '1班' },
                  { value: '2班', label: '2班' },
                  { value: '3班', label: '3班' }
                ]
              },
              {
                value: '2022级', label: '2022级',
                children: [
                  { value: '1班', label: '1班' },
                  { value: '2班', label: '2班' },
                  { value: '3班', label: '3班' }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

// 组织结构
const structures = [
  {
    value: '研发部', label: '研发部',
    children: [
      { value: 'AI算法', label: 'AI算法' },
      { value: '大数据', label: '大数据' },
      { value: '网络安全', label: '网络安全' },
    ]
  },
  {
    value: '部门1', label: '部门1',
    children: [
      { value: 'AI算法', label: 'AI算法' },
      { value: '大数据', label: '大数据' },
      { value: '网络安全', label: '网络安全' },
    ]
  },
  {
    value: '技术部', label: '技术部',
    children: [
      { value: '后端开发', label: '后端开发' },
      { value: '前端开发', label: '前端开发' },
    ]
  },
  {
    value: '市场部', label: '市场部',
    children: [
      { value: '数据分析', label: '数据分析' },
    ]
  },
  {
    value: '设计部', label: '设计部',
    children: [
      { value: '建筑设计', label: '建筑设计' },
    ]
  },
  {
    value: '产品部', label: '产品部',
    children: [
      { value: '软件开发', label: '软件开发' },
    ]
  },
]

// 用户数据 - 关联河南工业和信息化职业学院四级结构
const users = ref([])

// 显示的用户数据（经过搜索筛选后的数据）
const filteredUsers = ref([])

// 搜索状态
const isSearching = ref(false)

// 点击新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  resetForm()
  dialogVisible.value = true
  nextTick(() => {
    userFormRef.value?.clearValidate()
  })
}

// 获取用户详情
const getUserInfo = async (id) => {
  const res = await getUserInfoApi(id)
  if (res.code == 200) {
    return res.result
  } else {
    ElMessage.error(res.message)
    return null
  }
}

// 点击编辑用户按钮
const handleEdit = async (row) => {
  dialogTitle.value = '编辑用户'
  let user = await getUserInfo(row.id)
  if (!user) return ElMessage.error('获取用户详情失败')
  userForm.id = user.id
  userForm.name = user.name
  userForm.gender = user.gender
  userForm.userId = user.userId
  userForm.password = row.password
  userForm.hometown = user.hometown
  userForm.email = user.email
  userForm.weChatId = user.weChatId
  userForm.avatar = user.avatar
  userForm.telephone = user.telephone
  userForm.birthDate = user.birthDate
  userForm.classInfo = [user.school, user.faculty, user.major, user.grade, user.className]
  userForm.structure = user.structure.split('/')
  dialogVisible.value = true
}

// 点击查看用户详情
const handleView = (row) => {
  currentUser.value = { ...row }
  viewDialogVisible.value = true
}

// 点击删除单个用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除用户 "${row.name}" 吗？`, '提示', { type: 'warning' }).then(async () => {
    const ids = [row.id]
    const res = await deleteUserApi(ids)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await getUserList()
    }
    else ElMessage.error(res.message)}).catch(() => {
  })
}

// 点击批量删除用户
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定删除选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', { type: 'warning' }).then(async () => {
    let ids = []
    for (let user of selectedUsers.value) {
      ids.push(user.id)
    }
    const res = await deleteUserApi(ids)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await getUserList()
    }
    else ElMessage.error(res.message)}).catch(() => {})
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleSearch = () => {
  isSearching.value = true
  pagination.currentPage = 1

  // 执行搜索筛选
  let result = [...users.value]

  // 关键词搜索
  if (searchForm.keyword) {
    result = result.filter(user =>
        user.name.includes(searchForm.keyword) ||
        user.stuId.includes(searchForm.keyword) ||
        user.account.includes(searchForm.keyword)
    )
  }

  // 性别筛选
  if (searchForm.gender) {
    result = result.filter(user => user.gender === searchForm.gender)
  }

  // 组织结构筛选
  if (searchForm.organization && searchForm.organization.length) {
    // 将选择的组织结构数组转换为字符串，用于比较
    const selectedOrg = Array.isArray(searchForm.organization) ? searchForm.organization.join(',') : String(searchForm.organization)
    // 确保用户的组织结构包含选择的所有层级（前缀匹配）
    result = result.filter(u => {
      // 检查用户的组织结构文本是否以选择的组织结构开头
      return u.organizationText.startsWith(selectedOrg) ||
          // 或者用户的组织结构数组完全包含选择的组织结构数组
          (Array.isArray(searchForm.organization) &&
              searchForm.organization.every((level, index) => u.organization[index] === level))
    })
  }

  // 更新显示数据
  filteredUsers.value = result
  pagination.total = result.length

  // 更新分页显示
  updateDisplayData()

  ElMessage.success(`搜索完成，找到 ${result.length} 条记录`)
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.gender = ''
  searchForm.organization = undefined
  pagination.currentPage = 1
  isSearching.value = false
  pagination.total = users.value.length
  updateDisplayData()
  ElMessage.success('已重置搜索条件')
}

const handleSizeChange = (size) => {
}

const handleCurrentChange = (page) => {
}

// 更新显示数据（分页）
const updateDisplayData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  const dataSource = isSearching.value ? filteredUsers.value : users.value
  const paginatedData = dataSource.slice(start, end)
  filteredUsers.value = paginatedData
}

// 提交编辑用户或添加用户
const handleSubmit = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      if (dialogTitle.value == '编辑用户') {
        // 编辑
        userForm.formatBirthDate = dayjs(userForm.formatBirthDate).format('YYYY-MM-DD')
        const reqData = {
          id: userForm.id,
          name: userForm.name, gender: userForm.gender, userId: userForm.userId,
          password: userForm.password, hometown: userForm.hometown, email: userForm.email, weChatId: userForm.weChatId,
          school: userForm.classInfo[0], faculty: userForm.classInfo[1], major: userForm.classInfo[2],
          grade: userForm.classInfo[3], className: userForm.classInfo[4], avatar: userForm.avatar,
          telephone: userForm.telephone, birthDate: userForm.formatBirthDate, structure: userForm.structure[0] + '/' + userForm.structure[1]
        }
        const res = await editUserApi(reqData)
        if (res.code == 200) {
          ElMessage.success(res.message)
          getUserList()
          dialogVisible.value = false
        } else ElMessage.error(res.message)
      } else {
        // 新增
        userForm.formatBirthDate = dayjs(userForm.formatBirthDate).format('YYYY-MM-DD')
        const reqData = {name: userForm.name, gender: userForm.gender, userId: userForm.userId,
          password: userForm.password, hometown: userForm.hometown, email: userForm.email, weChatId: userForm.weChatId,
          school: userForm.classInfo[0], faculty: userForm.classInfo[1], major: userForm.classInfo[2],
          grade: userForm.classInfo[3], className: userForm.classInfo[4], avatar: userForm.avatar,
          telephone: userForm.telephone, birthDate: userForm.formatBirthDate, structure: userForm.structureText
        }
        const res = await addUserApi(reqData)
        if (res.code == 200) {
          ElMessage.success(res.message)
          getUserList()
          dialogVisible.value = false
        } else ElMessage.error(res.message)
      }
    }
  })
}

const handleDialogClose = () => {
  resetForm()
  userFormRef.value?.resetFields()
  userFormRef.value?.clearValidate()
}

// 表单重置
const resetForm = () => {
  Object.assign(userForm, {
    name: '',
    gender: '',
    userId: '',
    password: '',
    hometown: '',
    email: '',
    weChatId: '',
    classInfo: [],
    classInfoText: '',
    avatar: 'https://placehold.co/100x100',
    telephone: '',
    birthDate: '',
    structure: [],
    structureText: ''
  })
}

const handleOrganizationChange = (value) => {
  userForm.organizationText = value.join(',')
}

const handleStructureChange = (value) => {
  userForm.structureText = value.join('/')
}

const handleImport = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = utils.read(data, { type: 'array' })
      const worksheet = workbook.Sheets[workbook.SheetNames[0]]
      const jsonData = utils.sheet_to_json(worksheet)

      // 处理导入的数据
      const importedUsers = jsonData.map((item, index) => ({
        // id: Date.now() + index,
        // name: item['姓名'] || '',
        // gender: item['性别'] || '保密',
        // stuId: item['学号'] || '',
        // account: item['账号'] || '',
        // password: item['密码'] || '123456',
        // contact: item['联系方式'] || '-',
        // organization: item['所属组织'] ? item['所属组织'].split(',') : [],
        // organizationText: item['所属组织'] || '',
        // lastLogin: item['最后登录'] || new Date().toLocaleString()
      }))

      users.value = [...importedUsers, ...users.value]
      ElMessage.success(`成功导入 ${importedUsers.length} 条用户数据`)
    } catch (error) {
      ElMessage.error('导入失败，请检查文件格式')
    }
  }
  reader.readAsArrayBuffer(file.raw)
}

const handleExport = () => {
  const exportData = users.value.map(user => ({
    // '姓名': user.name,
    // '性别': user.gender,
    // '学号': user.stuId,
    // '账号': user.account,
    // '密码': user.password,
    // '联系方式': user.contact,
    // '所属组织': user.organizationText,
    // '最后登录': user.lastLogin
  }))

  const ws = utils.json_to_sheet(exportData)
  const wb = utils.book_new()
  utils.book_append_sheet(wb, ws, '用户数据')
  writeFileXLSX(wb, '用户数据.xlsx')
  ElMessage.success('导出成功')
}
</script>

<template>
  <div class="user-management-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <AuthButton type="primary" permission="user:management:add" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </AuthButton>
        <AuthButton type="success" permission="user:management:export" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </AuthButton>
        <el-upload
            class="upload-demo"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImport"
            accept=".xlsx, .xls"
        >
          <AuthButton type="warning" permission="user:management:import">
            <el-icon><Upload /></el-icon>
            导入
          </AuthButton>
        </el-upload>
        <AuthButton type="danger" permission="user:management:batchDelete" @click="handleBatchDelete" :disabled="selectedUsers.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </AuthButton>
      </div>
      <div class="toolbar-right">
        <el-input
            v-model="searchForm.keyword"
            placeholder="请输入姓名、账号"
            style="width: 200px; margin-right: 10px"
            @keyup.enter="handleSearch"
            clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="searchForm.gender" placeholder="性别" style="width: 100px; margin-right: 10px" clearable>
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
        <el-cascader
            v-model="searchForm.organization"
            :options="organizationOptions"
            placeholder="组织结构"
            clearable
            style="width: 260px; margin-right: 10px"
        />
        <AuthButton type="primary" permission="user:management:search" @click="handleSearch">搜索</AuthButton>
        <AuthButton @click="handleReset" permission="user:management:reset">重置</AuthButton>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userList" v-loading="loading" @selection-change="handleSelectionChange" style="width: 100%" height="430">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.gender === '男' ? 'primary' : scope.row.gender === '女' ? 'success' : 'info'">
            {{ scope.row.gender }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="账号" width="120" />
      <el-table-column label="班级" min-width="580" >
        <template #default="scope">
          {{ scope.row.school + '/' + scope.row.faculty + '/' + scope.row.major + '/' + scope.row.grade + '/' + scope.row.className }}
        </template>
      </el-table-column>
      <el-table-column prop="structure" label="组织结构" min-width="200" />
      <el-table-column prop="updateTime" label="更新时间" min-width="200" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <AuthButton type="primary" link @click="handleEdit(scope.row)" permission="user:management:edit">编辑</AuthButton>
          <AuthButton type="info" link @click="handleView(scope.row)" permission="user:management:view">查看</AuthButton>
          <AuthButton type="danger" link @click="handleDelete(scope.row)" permission="user:management:delete">删除</AuthButton>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPageNum"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加用户和编辑用户的对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose" :destroy-on-close="true">
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="userId">
              <el-input v-model="userForm.userId" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="居住地址" prop="hometown">
              <el-input v-model="userForm.hometown" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="微信号" prop="weChatId">
              <el-input v-model="userForm.weChatId" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telephone">
              <el-input v-model="userForm.telephone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组织结构" prop="structure">
              <el-cascader v-model="userForm.structure" :options="structures" placeholder="请选择所属组织结构" style="width: 100%" @change="handleStructureChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="classInfo">
              <el-cascader v-model="userForm.classInfo" :options="classStore.classList" placeholder="请选择所属班级" style="width: 100%" @change="handleOrganizationChange"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker v-model="userForm.birthDate" type="date" placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <AuthButton @click="dialogVisible = false">取消</AuthButton>
        <AuthButton type="primary" @click="handleSubmit">确定</AuthButton>
      </template>
    </el-dialog>

    <!-- 展示用户详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="用户详情" width="1000px">
      <el-descriptions :column="4" border width="100%">
        <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentUser.gender }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <img :src="currentUser.avatar" alt="" width="30px">
        </el-descriptions-item>
        <el-descriptions-item label="学号">{{ currentUser.userId }}</el-descriptions-item>
        <el-descriptions-item label="居住地址">{{ currentUser.hometown }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="微信号">{{ currentUser.weChatId }}</el-descriptions-item>
        <el-descriptions-item label="所属班级">{{ currentUser.school + '/' + currentUser.faculty + '/' + currentUser.major + '/' + currentUser.grade + '/' + currentUser.className }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.telephone }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ currentUser.birthDate }}</el-descriptions-item>
        <el-descriptions-item label="组织结构">{{ currentUser.structure }}</el-descriptions-item>
        <el-descriptions-item label="用户创建时间">{{ currentUser.createTime }}</el-descriptions-item>
        <el-descriptions-item label="最近更新时间">{{ currentUser.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-management-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;

  .toolbar-left {
    display: flex;
    gap: 8px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  padding-top: 10px;
}

.upload-demo {
  display: inline-block;
}
</style>
